<?php
/**
 * Created by jinqiang on 2024/11/18 13:43.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Callback;


use App\Http\Models\Mysql\NnyyUserTable;
use App\Http\Models\Mysql\SsyAdditionalAmountTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseListTable;
use App\Http\Models\Mysql\SsyAllocationOrderListTable;
use App\Http\Models\Mysql\SsyAllocationOrderReturnTable;
use App\Http\Models\Mysql\SsyAllocationOrderTable;
use App\Http\Models\Mysql\SsyAllocationReportingListTable;
use App\Http\Models\Mysql\SsyAllocationSaleListTable;
use App\Http\Models\Mysql\SsyFeishuApprovalBindingTable;
use App\Http\Models\Mysql\SsyFeishuUserJsTable;
use App\Http\Models\Mysql\SsyFeishuUserMzTable;
use App\Http\Models\Mysql\SsyFeishuUserQyxTable;
use App\Http\Models\Mysql\SsyFeishuUserTable;
use App\Http\Models\Mysql\SsyFeishuUserXmTable;
use App\Http\Models\Mysql\SsyFeishuUserYxTable;
use App\Http\Models\Mysql\SsyFineAmountTable;
use App\Http\Models\Mysql\SsyPricingContractTable;
use App\Http\Models\Mysql\SsyPricingExamineTable;
use App\Http\Models\Mysql\SsyProcessingListShenqingTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Repository\ApprovalRepository;
use App\Http\Repository\FeishuRepository;
use App\Http\Repository\OmsRepository;
use App\Http\Repository\WmsRepository;
use App\Http\Services\Op\LendService;
use App\Http\Services\Produce\ProcessingService;
use App\Http\Services\Soa\ContractService;

class FeiShuService
{
    public static function feishuTable($tab)
    {
        switch ($tab){
            case 'kz':
                return new SsyFeishuUserTable();
            case 'mz':
                return new SsyFeishuUserMzTable();
            case 'yx':
                return new SsyFeishuUserYxTable();
            case 'xm':
                return new SsyFeishuUserXmTable();
            case 'js':
                return new SsyFeishuUserJsTable();
            case 'qyx':
                return new SsyFeishuUserQyxTable();
        }
    }

    public function getMessage($param, $sub)
    {
        try{
            //通讯录事件 用户更新
            if($param['header']['event_type'] ?? "" && $param['header']['event_type']=='contact.user.updated_v3'){
                $data = [
                    "name" => $param['event']['object']['name'],
                    "union_id" => $param['event']['object']['union_id'],
                    "user_id" => $param['event']['object']['user_id'],
                    "work_station" => $param['event']['object']['work_station'] ?? "",
                    "status" => json_encode($param['event']['object']['status'], JSON_UNESCAPED_UNICODE),
                    //"orders" => json_encode($param['event']['object']['orders'] ?? ""),
                    "open_id" => $param['event']['object']['open_id'],
                    //"mobile_visible" => $param['event']['object']['name'],
                    "mobile" => $param['event']['object']['mobile'],
                    "join_time" => isset($param['event']['object']['join_time']) ? date('Y-m-d H:i:s', $param['event']['object']['join_time']) : "",
                    "job_title" => $param['event']['object']['job_title'] ?? "",
                    "gender" => $param['event']['object']['gender'] ?? 0,
                    "en_name" => $param['event']['object']['en_name'] ?? "",
                    "employee_type" => $param['event']['object']['employee_type'] ?? 1,
                    "employee_no" => $param['event']['object']['employee_no'] ?? "",
                    //"department_ids" => json_encode($param['event']['object']['department_ids'] ?? ""),
                    "leader_user_id" =>$param['event']['object']['leader_user_id'] ?? "",
                    "country" =>$param['event']['object']['country'] ?? "",
                    "city" =>$param['event']['object']['city'] ?? "",
                    //"avatar" => json_encode($param['event']['object']['avatar'] ?? ""), //头像信息
                    "createtime" => date("Y-m-d H:i:s")
                ];
                $userObj = (self::feishuTable($sub))->where('user_id', $param['event']['object']['user_id'])->first();
                if(!empty($userObj)){
                    //判断是否修改了手机号，需同步用户主表的手机号及登录密码
                    if($data['mobile'] != $userObj->mobile){
                        $mobile = substr($data['mobile'], 3);
                        $nnyyUserObj = (new NnyyUserTable())->where(['name' => $data['name'], 'phone' => $mobile])->first();
                        if(!empty($nnyyUserObj)){
                            (new NnyyUserTable())->updateData($nnyyUserObj->id, ['phone' => $mobile, 'password' => bcrypt($mobile)]);
                        }
                    }
                    unset($data['createtime']);
                    return (self::feishuTable($sub))->updateData($userObj->id, $data);
                }else{
                    return (self::feishuTable($sub))->createData($data);
                }
            }
            //通讯录事件 人员离职
            if($param['header']['event_type'] ?? "" && $param['header']['event_type']=='contact.user.deleted_v3'){
                $userObj = (self::feishuTable($sub))->where('user_id', $param['event']['object']['user_id'])->first();
                if(!empty($userObj)){
                    return (self::feishuTable($sub))->updateData($userObj->id, [
                        'status' => json_encode($param['event']['object']['status'], JSON_UNESCAPED_UNICODE)
                    ]);
                }
                return ['code' => 0];
            }
            //实例审核过程事件
            if($param['event']['type'] == 'approval_task' && $param['event']['status'] == 'APPROVED'){
                //生产采购合同--某人同意后自动发送签署
                if(in_array($param['event']['approval_code'], ['B5FFB31E-1692-4710-929D-565B18C03F4F','69D9D85A-2F64-4FD9-90DF-A957D7F867E8'])){
                    $userObj = (new NnyyUserTable())->where("kz_feishu_user_id", $param['event']['user_id'])->first();
                    if(in_array($userObj->name ?? "", ['王蓝苹'])){
                        $approvalObj = (new SsyFeishuApprovalBindingTable())->where('instance_code', $param['event']['instance_code'])->first()->toArray();
                        return (new ContractService())->pushSignature((Int)$approvalObj['data_id']);
                    }
                }
                //销售退货--仓库人员通过后推送调拨计划单
                if(in_array($param['event']['approval_code'], ['753572F5-397A-49E8-9E04-FAAD8702742F'])){
                    $userObj = (new NnyyUserTable())->where("kz_feishu_user_id", $param['event']['user_id'])->first();
                    if(in_array($userObj->name ?? "", ['刘聪聪'])){
                        $approvalObj = (new SsyFeishuApprovalBindingTable())->where('instance_code', $param['event']['instance_code'])->first()->toArray();
                        return WmsRepository::pushAllocation($approvalObj['data_id'], $sub);//推送巨沃
                    }
                }
            }
            //实例审批结果事件
            if($param['event']['type'] == 'approval_instance'){
                $eventStatus = [
                    //'PENDING' => 0,  // 进行中
                    'APPROVED' => 1,  // 已通过
                    'REJECTED' => 2,  // 已拒绝
                    'CANCELED' => 3,  // 已撤回
                    'REVERTED' => 4,  // 已撤销
                    'DELETED'  => 5   // 已删除
                ];
                if(!isset($eventStatus[$param['event']['status']])){
                    return [ 'code' => -1, 'msg' => "不在审批状态内: event.status:".$param['event']['status']];
                }
                $approvalList = (new SsyFeishuApprovalBindingTable())->where('instance_code', $param['event']['instance_code'])->get()->toArray();
                foreach ($approvalList as $item){
                    //1借、2还、3赠、14销售
                    if(in_array($item['types'], [1, 2, 3, 14])){
                        $res = (new SsyAllocationOrderListTable())->updateDataWhere(['allocation_number' => $item['data_id']], [
                            'status' => $eventStatus[$param['event']['status']],
                            'examinetime' => date("Y-m-d H:i:s")
                        ]);
                        //推送巨沃 & 推送金蝶
                        if($res['code'] === 0 && $eventStatus[$param['event']['status']] == 1){
                            WmsRepository::pushAllocation($item['data_id'], $sub);//推送巨沃
                            //推送金蝶
                            $postData = ['timeout' => 1, 'json' => ['allocation_number' => $item['data_id'], 'sub' => $sub]];
                            httpCurl(config("app.url")."/api/ext/kingdee/pushAllocation", $postData);
                        }
                        //撤销逻辑
                        if($res['code'] === 0 && $eventStatus[$param['event']['status']] == 4){
                            (new LendService())->cancel($item['data_id']);
                        }
                    }
                    //4内购
                    if($item['types'] == 4){
                        $res = (new SsyAllocationIpurchaseListTable())->updateDataWhere(['allocation_number' => $item['data_id']], [
                            'status' => $eventStatus[$param['event']['status']],
                            'examinetime' => date("Y-m-d H:i:s")
                        ]);
                        //普通内购 需推送巨益
                        if($res['code'] === 0 && $eventStatus[$param['event']['status']] == 1){
                            $ipurchaseObj = (new SsyAllocationIpurchaseListTable())->where('allocation_number', $item['data_id'])->first();
                            if(!empty($ipurchaseObj) && $ipurchaseObj->types == 0){//内购
                                OmsRepository::pushAllocation($ipurchaseObj);
                            }
                            if(!empty($ipurchaseObj) && $ipurchaseObj->types == 1){//借转内购
                                WmsRepository::pushAllocationS($item['data_id'], $sub);
                                //推送金蝶
                                $postData = ['timeout' => 1, 'json' => ['allocation_number' => $item['data_id'], 'sub' => $sub]];
                                httpCurl(config("app.url")."/api/ext/kingdee/pushAllocationN", $postData);
                            }
                        }
                    }
                    //5加工单增裁
                    if($item['types'] == 5){
                        $res = (new SsyProcessingListShenqingTable())->updateDataWhere(['new_processing_code' => $item['data_id']], [
                            'status' => $eventStatus[$param['event']['status']]
                        ]);
                        //生成增裁加工单 & 推送巨益
                        if($res['code'] === 0 && $eventStatus[$param['event']['status']] == 1){
                            $addRes = (new ProcessingService())->zengcCreate($item['data_id']);
                            if($addRes['code'] === 0){
                                list($pushRes, ) = OmsRepository::push($item['data_id']);
                                if($pushRes['code'] === 0){
                                    $save = [
                                        'is_oms' => 1,
                                        'jy_number' => $pushRes['data']['entryOrderId']
                                    ];
                                    (new SsyProcessingListTable())->updateDataWhere(['processing_code' => $item['data_id']], $save);
                                }
                            }
                        }
                    }
                    //6报次
                    if($item['types'] == 6){
                        (new SsyAllocationReportingListTable())->updateDataWhere(['allocation_number' => $item['data_id']], [
                            'status' => $eventStatus[$param['event']['status']],
                            'examinetime' => date("Y-m-d H:i:s")
                        ]);
                    }
                    //7借转送 8送转还
                    if(in_array($item['types'], [7, 8])){
                        $res = (new SsyAllocationOrderListTable())->updateDataWhere(['allocation_number' => $item['data_id']], [
                            'status' => $eventStatus[$param['event']['status']],
                            'examinetime' => date("Y-m-d H:i:s")
                        ]);
                        if($res['code'] === 0 && $eventStatus[$param['event']['status']] == 1){
                            //送转还 需推送巨沃
                            if($item['types'] == 8){
                                WmsRepository::pushAllocation($item['data_id'], $sub);
                            }
                            //借转送
                            if($item['types'] == 7){
                                //推送金蝶
                                $postData = ['timeout' => 1, 'json' => ['allocation_number' => $item['data_id'], 'sub' => $sub]];
                                httpCurl(config("app.url")."/api/ext/kingdee/pushAllocation", $postData);
                            }
                        }
                    }
                    //10借转销售
                    if($item['types'] == 10){
                        $res = (new SsyAllocationSaleListTable())->updateDataWhere(['allocation_number' => $item['data_id']], [
                            'status' => $eventStatus[$param['event']['status']]
                        ]);
                        if($res['code'] === 0 && $eventStatus[$param['event']['status']] == 1){
                            WmsRepository::pushAllocationS($item['data_id'], $sub);
                            //推送金蝶
                            $postData = ['timeout' => 1, 'json' => ['allocation_number' => $item['data_id'], 'sub' => $sub]];
                            httpCurl(config("app.url")."/api/ext/kingdee/pushAllocationS", $postData);
                        }
                    }
                    //20核价单审核
                    if($item['types'] == 20){
                        $eventStatus = [
                            'APPROVED' => 2,  // 已通过
                            'REJECTED' => 3,  // 已拒绝
                            'REVERTED' => 4,  // 已撤销
                            'DELETED'  => 4,   // 已删除
                            'CANCELED' => 5  // 已撤回
                        ];
                        (new SsyPricingExamineTable())->updateData((Int)$item['data_id'], [
                            'status' => $eventStatus[$param['event']['status']],
                            'examinetime' => date("Y-m-d H:i:s")
                        ]);
                        if(in_array($eventStatus[$param['event']['status']], [2, 3])){
                            $examineObj = (new SsyPricingExamineTable())->where('id', (Int)$item['data_id'])->first()->toArray();
                            ApprovalRepository::setReturnsPrice($examineObj, 2);
                        }
                    }
                    //21违约赔偿审核
                    if($item['types'] == 21){
                        (new SsyFineAmountTable())->updateData((Int)$item['data_id'], [
                            'status' => $eventStatus[$param['event']['status']],
                            'examinetime' => date("Y-m-d H:i:s")
                        ]);
                    }
                    //22额外费用审核
                    if($item['types'] == 22){
                        (new SsyAdditionalAmountTable())->updateData((Int)$item['data_id'], [
                            'status' => $eventStatus[$param['event']['status']],
                            'examinetime' => date("Y-m-d H:i:s")
                        ]);
                    }
                    //23生产采购合同审核
                    if($item['types'] == 23){
                        $eventStatus = [
                            'APPROVED' => 2,  // 已通过
                            'REJECTED' => 3,  // 已拒绝
                            'REVERTED' => 4,  // 已撤销
                            'DELETED'  => 4,   // 已删除
                            'CANCELED' => 5  // 已撤回
                        ];
                        (new SsyPricingContractTable())->updateData((Int)$item['data_id'], [
                            'status' => $eventStatus[$param['event']['status']],
                            'zs_time' => date("Y-m-d H:i:s")
                        ]);
                    }
                }
                return ['code' => 0, 'msg' => '回调内容已处理', 'data' => $res ?? []];
            }
            return ['code' => -1, 'msg' => '未知审批类型'];
        }catch (\Exception $e){
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    //发送消息--调拨借、赠
    public function pushAllocationMsg($allocationNumber, $courierNumber)
    {
        //计划数量
        $planNum = (new SsyAllocationOrderTable())->where('allocation_number', $allocationNumber)->sum('num');
        //调拨单据
        $allocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $allocationNumber)->first();
        if(empty($allocationObj)){
            return ['code' => -1, 'msg' => '无对应调拨单据: '.$allocationNumber];
        }
        $allocationObj = $allocationObj->toArray();
        $isSubject = $allocationObj['is_subject'] ?: "kz";
        $userObj = (new NnyyUserTable())->where('name', $allocationObj['adduser'])->first();
        if(empty($userObj)){
            return ['code' => -1, 'msg' => '未找到用户消息'];
        }
        $userObj = $userObj->toArray();
        $fsUserid = $userObj[$isSubject . "_feishu_user_id"];
        $subjects = array_column(config("scm.subject"), 'fs_message_temp_id', 'is_subject');
        $title = $allocationObj['groups'] == 2 ? '借出':'赠送';
        $postData = [
            'receive_id' => $fsUserid,
            'msg_type' => 'interactive',
            'content' => json_encode([
                'type' => 'template',
                'data' => [
                    'template_id' => $subjects[$isSubject],
                    'template_variable' => [
                        'title' => $title,
                        'allocationNumber' => $allocationNumber,
                        'num' => $planNum.' / '.$planNum,
                        'wp_user' => $allocationObj['wp_user'],
                        'create_time' => date('Y-m-d H:i:s'),
                        'user_id' => $fsUserid,
                        'courierNumber' => $courierNumber
                    ]
                ]
            ], JSON_UNESCAPED_UNICODE),
        ];
        $res = (new FeishuRepository($isSubject))->sendMsg($postData);
        return ['code' => 0, 'msg' => '已发送', 'data' => $res];
    }
}
